import React, { useState, useRef, useEffect } from 'react'
import { Input, Button, Card, Spin, message, Alert } from 'antd'
import { SendOutlined, RobotOutlined, UserOutlined } from '@ant-design/icons'
import apiService from '../services/api'

const { TextArea } = Input

function ChatBox({ backendStatus }) {
  const [messages, setMessages] = useState([
    {
      id: 1,
      type: 'bot',
      content: '您好！我是AI智能客服助理。我可以帮您：\n\n• 📋 查询订单状态\n• 🧾 识别发票信息\n• 💰 处理退款申请\n• 🎤 支持语音输入\n\n请告诉我您需要什么帮助？',
      timestamp: new Date(),
    }
  ])
  const [inputValue, setInputValue] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [uploadedImage, setUploadedImage] = useState(null)
  const messagesEndRef = useRef(null)

  // 自动滚动到底部
  useEffect(() => {
    scrollToBottom()
  }, [messages])

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  // 发送消息
  const handleSend = async () => {
    if (!inputValue.trim() && !uploadedImage) {
      message.warning('请输入消息或上传图片')
      return
    }

    if (backendStatus?.status === 'offline') {
      message.error('后端服务不可用，请稍后重试')
      return
    }

    const userMessage = {
      id: Date.now(),
      type: 'user',
      content: inputValue || '上传了图片',
      image: uploadedImage,
      timestamp: new Date(),
    }

    setMessages(prev => [...prev, userMessage])
    setInputValue('')
    setIsLoading(true)

    try {
      const response = await apiService.sendMessage(inputValue, uploadedImage)

      if (response.success) {
        const botMessage = {
          id: Date.now() + 1,
          type: 'bot',
          content: response.data.answer,
          thought: response.data.thought,
          action: response.data.action,
          observation: response.data.observation,
          timestamp: new Date(),
          processingTime: response.processing_time
        }

        setMessages(prev => [...prev, botMessage])
      } else {
        throw new Error(response.error || '请求失败')
      }
    } catch (error) {
      console.error('Send message error:', error)
      const errorMessage = {
        id: Date.now() + 1,
        type: 'error',
        content: `抱歉，处理您的请求时出现错误：${error.message}`,
        timestamp: new Date(),
      }
      setMessages(prev => [...prev, errorMessage])
    } finally {
      setIsLoading(false)
      setUploadedImage(null)
    }
  }

  // 处理键盘事件
  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSend()
    }
  }

  // 渲染消息
  const renderMessage = (msg) => {
    const isUser = msg.type === 'user'
    const isError = msg.type === 'error'

    return (
      <Card
        key={msg.id}
        className={`message-card ${isUser ? 'message-user' : 'message-bot'}`}
        style={{
          marginLeft: isUser ? 'auto' : '0',
          marginRight: isUser ? '0' : 'auto',
          maxWidth: '70%',
          background: isError ? '#fff1f0' : isUser ? '#1890ff' : 'white',
          border: isError ? '1px solid #ffccc7' : 'none'
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
          {isUser ? (
            <UserOutlined style={{ color: 'white', marginRight: 8 }} />
          ) : (
            <RobotOutlined style={{ color: '#1890ff', marginRight: 8 }} />
          )}
          <span style={{ fontSize: 12, color: isUser ? 'rgba(255,255,255,0.8)' : '#666' }}>
            {msg.timestamp.toLocaleTimeString()}
          </span>
        </div>

        {/* AI 思考过程 */}
        {msg.thought && (
          <div className="thought-process">
            <strong>🤔 思考：</strong> {msg.thought}
          </div>
        )}

        {/* 执行动作 */}
        {msg.action && (
          <div className="action-info">
            <strong>⚡ 执行：</strong> {msg.action}
          </div>
        )}

        {/* 观察结果 */}
        {msg.observation && (
          <div className="observation-info">
            <strong>👁️ 结果：</strong> {msg.observation}
          </div>
        )}

        {/* 消息内容 */}
        <div
          style={{
            color: isUser ? 'white' : '#333',
            whiteSpace: 'pre-wrap',
            lineHeight: 1.6
          }}
          dangerouslySetInnerHTML={{
            __html: msg.content.replace(/\n/g, '<br>')
          }}
        />

        {/* 处理时间 */}
        {msg.processingTime && (
          <div style={{
            fontSize: 12,
            color: isUser ? 'rgba(255,255,255,0.6)' : '#999',
            marginTop: 8
          }}>
            处理时间: {msg.processingTime}
          </div>
        )}

        {/* 显示上传的图片 */}
        {msg.image && (
          <div style={{ marginTop: 12 }}>
            <img
              src={URL.createObjectURL(msg.image)}
              alt="上传的图片"
              style={{
                maxWidth: '100%',
                maxHeight: 200,
                borderRadius: 8,
                border: '1px solid #f0f0f0'
              }}
            />
          </div>
        )}
      </Card>
    )
  }

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* 消息区域 */}
      <div className="chat-messages">
        {messages.map(renderMessage)}

        {/* 加载状态 */}
        {isLoading && (
          <Card className="message-card message-bot" style={{ maxWidth: '70%' }}>
            <div className="loading-spinner">
              <div className="thinking-animation"></div>
              AI 正在思考中...
            </div>
          </Card>
        )}

        <div ref={messagesEndRef} />
      </div>

      {/* 输入区域 */}
      <div className="chat-input-area">
        {/* 图片预览 */}
        {uploadedImage && (
          <div style={{ marginBottom: 12 }}>
            <Alert
              message="已选择图片"
              description={`${uploadedImage.name} (${(uploadedImage.size / 1024).toFixed(1)} KB)`}
              type="info"
              showIcon
              closable
              onClose={() => setUploadedImage(null)}
            />
          </div>
        )}

        {/* 文本输入 */}
        <div style={{ display: 'flex', gap: 12 }}>
          <TextArea
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="输入您的消息，或上传发票图片..."
            autoSize={{ minRows: 2, maxRows: 6 }}
            style={{ flex: 1 }}
            disabled={isLoading}
          />

          <Button
            type="primary"
            icon={<SendOutlined />}
            onClick={handleSend}
            loading={isLoading}
            disabled={!inputValue.trim() && !uploadedImage}
            style={{ height: 'auto', padding: '4px 12px' }}
          >
            发送
          </Button>
        </div>

        {/* 输入提示 */}
        <div style={{ marginTop: 8, fontSize: 12, color: '#999' }}>
          💡 提示：按 Enter 发送，Shift + Enter 换行
        </div>
      </div>
    </div>
  )
}

export default ChatBox
